<template>
  <inline-Modal
    :visible="visible"
    :title="filterTitle()"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="submitLoading"
      @click="handelOk()"
      v-if="pageOperate == 2"
    >
      确定
    </a-button>
    <div class="wrapPage-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <!-- 基本信息 -->
        <div class="warp-container">
          <!-- <a-form-model-item label="项目名称">
            <a-select v-model="form.proCode" disabled>
              <a-select-option
                :value="item.proCode"
                v-for="item in projectSoucre"
                :key="item.uuid"
              >
                {{ item.proName }}
              </a-select-option>
            </a-select>
          </a-form-model-item> -->
          <a-form-model-item label="名称">
            <a-input v-model="form.name" disabled></a-input>
          </a-form-model-item>
          <a-row :gutter="0">
            <a-col :span="8">
              <a-form-model-item label="时间">
                <a-date-picker
                  placeholder=" "
                  style="width: 100%"
                  v-model="form.time"
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="地点">
                <a-input v-model="form.location" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="专业">
                <a-select v-model="form.major" disabled>
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in majorSource"
                    :key="item.dicItemCode"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item label="参会人员">
            <a-tree-select
              multiple
              disabled
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="participantsSource"
              :replaceFields="{
                children: 'children',
                title: 'text',
                key: 'value',
                value: 'value',
              }"
              v-model="form.participantsIds"
            />
          </a-form-model-item>
          <a-form-model-item label="图纸/模型">
            <div class="base-container">
              <div class="base-left">
                <div class="tree-container">
                  <a-empty v-if="treeData.length == 0" :description="false" />
                  <a-tree
                    v-else
                    v-model="checkedKeys"
                    show-icon
                    show-line
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    :selected-keys="selectedKeys"
                    :tree-data="treeData"
                    :replaceFields="{
                      children: 'children',
                      title: 'nodeName',
                      key: 'uuid',
                    }"
                    @expand="onExpand"
                    @select="onSelect"
                  >
                    <!-- 自定义图标 -->
                    <template slot="custom" slot-scope="{ expanded }">
                      <a-icon
                        :type="expanded ? 'folder-open' : 'folder'"
                        theme="filled"
                      />
                    </template>
                    <template slot="title" slot-scope="{ nodeName }">
                      <div class="custom-tree-title-warp">
                        <div class="title" :title="nodeName">
                          {{ nodeName }}
                        </div>
                      </div>
                    </template>
                  </a-tree>
                </div>
              </div>
              <div class="base-right">
                <div class="upload-groups">
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    icon="download"
                    @click="handleDownloadZip()"
                    :loading="downloadLoading"
                    :disabled="downloadLoading"
                  >
                    {{ downloadLoading ? "下载中" : "下载" }}
                  </a-button>
                </div>
                <div class="table-file-container">
                  <vxe-table
                    ref="xTable"
                    height="99%"
                    align="center"
                    show-overflow
                    show-header-overflow
                    :data="tableData"
                    :column-config="{ resizable: true }"
                    size="small"
                    :loading="tableLoading"
                  >
                    <vxe-column type="seq" width="80" title="序号"></vxe-column>
                    <vxe-column
                      field="fileName"
                      title="文件名称"
                      align="left"
                      min-width="300"
                    >
                      <template #default="{ row }">
                        <div class="table-file-name">
                          <div
                            class="icon"
                            :class="[getFileIconName(row.fileName)]"
                          ></div>
                          <div class="name" @click="previewFile(row)">
                            {{ row.fileName }}
                          </div>
                        </div>
                      </template>
                    </vxe-column>
                    <vxe-column field="commentUsersName" title="批注负责人">
                    </vxe-column>
                    <vxe-column field="creator" title="上传人"> </vxe-column>
                    <vxe-column field="createTimeStr" title="上传时间">
                    </vxe-column>
                    <vxe-column
                      field="operate"
                      fixed="right"
                      width="130"
                      title="操作"
                    >
                      <template #default="{ row}">
                        <div class="files-icon">
                          <!-- 预览 -->
                          <a-tooltip placement="top">
                            <template slot="title">
                              预览
                            </template>
                            <a-icon type="eye" @click="previewFile(row)" />
                          </a-tooltip>
                          <!-- 下载 -->
                          <a-tooltip placement="top">
                            <template slot="title">
                              下载
                            </template>
                            <a-icon
                              type="download"
                              @click="downloadFile(row, 1)"
                            />
                          </a-tooltip>
                        </div>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </div>
            </div>
          </a-form-model-item>
          <a-form-model-item label="其他文件">
            <bjUploadFile
              :viewMode="true"
              :count="20"
              v-model="form.otherDocuments"
              @preview="viewFile($event)"
              @download="downloadFile($event, 2)"
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>
          <a-form-model-item label="备注" prop="tenantCode">
            <a-textarea :rows="4" v-model="form.remark" disabled />
          </a-form-model-item>
          <a-form-model-item label="图纸会审纪要">
            <bjUploadFile
              :viewMode="true"
              :count="20"
              v-model="form.jointReview"
              @preview="viewFile($event)"
              @download="downloadFile($event, 2)"
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>
          <template v-if="form.approveStatus != 0">
            <a-form-model-item label="问题清单">
              <a-button type="primary" @click="handleProblem()">
                查看详情
              </a-button>
            </a-form-model-item>
            <a-form-model-item label="处理意见表">
              <a-button type="primary" @click="handleOpinion()">
                查看详情
              </a-button>
            </a-form-model-item>
            <a-row :gutter="0">
              <a-col :span="8">
                <a-form-model-item label="创建人">
                  <a-input v-model="parameter.creator" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="创建时间">
                  <a-input v-model="parameter.createTime" disabled></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </template>
        </div>
        <!-- 审批数据 -->
        <template v-if="pageOperate == 2">
          <a-divider />
          <div class="warp-container">
            <a-form-model-item
              label="审批结果"
              prop="operate"
              :rules="{
                required: true,
                message: '请选择审批结果',
              }"
            >
              <a-radio-group v-model="form.operate">
                <a-radio :value="2">
                  通过
                </a-radio>
                <a-radio :value="3">
                  驳回
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="审批意见" prop="reason">
              <a-textarea
                placeholder="请输入"
                :rows="4"
                v-model="form.reason"
              />
            </a-form-model-item>
          </div>
        </template>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </inline-Modal>
</template>

<script>
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import {
  getToken,
  downloadDfs,
  downLoadBatchFileByArraybuffer,
} from "@/utils/TopVUI";
import {
  addAttributeByKey,
  flatTreeData,
  getFileIconName,
} from "@/utils/util.js";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
//普通附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";

import { getDicItemByCode, getAllProListByQX } from "@/api/common.js";
import {
  detailDrawingReview,
  exportZip67,
  approveDrawingReview,
  participantsList,
} from "@/api/design";
export default {
  provide() {
    return {
      moduleSource: () => this.pageModule,
    };
  },
  components: {
    IconFont,
    previewModal,
    bjUploadFile,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //1查看 2审批
    pageOperate: {
      type: [String, Number],
      default: 1,
    },
  },
  data() {
    return {
      pageModule: 7,
      //项目名称
      projectSoucre: [],
      //专业
      majorSource: [],
      //参会人员
      participantsSource: [],
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //图纸管理
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      currentTreeNode: {},
      //表单
      submitLoading: false,
      form: {
        uuid: "",
        //项目名称
        proCode: undefined,
        //交底名称
        name: "",
        //时间
        time: "",
        //地点
        location: "",
        //专业
        major: undefined,
        //图纸/模型
        fileSource: 1,
        //引用
        type: 3,
        //引用文件
        quoteFiles: "",
        //图纸会审纪要
        jointReview: [],
        //其他文件
        otherDocuments: [],
        //备注
        remark: "",
        //审批结果
        operate: "",
        //审批意见
        reason: "",
        //参会人员
        participantsIds: [],
        //审批状态
        approveStatus: "",
      },
      rules: {},
      //表格
      tableData: [],
      tableLoading: false,
      //下载
      downloadLoading: false,
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getFileIconName,
    //问题清单
    handleProblem() {
      this.$parent.previewProblem(this.parameter);
    },
    //处理意见表
    handleOpinion() {
      this.$parent.previewOpinion(this.parameter);
    },
    getData() {
      Promise.all([this.getTypeData(), this.getDetail()])
        .then(() => {})
        .catch(() => {});
    },

    //下载压缩包
    handleDownloadZip() {
      let { id, nodeName } = this.currentTreeNode;
      let { uuid } = this.form;
      this.downloadLoading = true;
      exportZip67({ uuid, classifyId: id, type: this.pageModule })
        .then((data) => {
          downLoadBatchFileByArraybuffer(data, nodeName);
        })
        .catch((_) => {})
        .finally((_) => {
          this.downloadLoading = false;
        });
    },

    //交底文件预览
    previewFile(row) {
      let { previewWay, uuid, fileInfo, unit, bhDataSetId } = row;
      let { fileName, url } = fileInfo;
      let domain = location.origin;
      switch (previewWay) {
        //cad预览
        case "cad":
          window.open(
            `${domain}/#/blackHole/previewCad?uuid=${uuid}&fileName=${fileName}&unit=${unit}`
          );
          return;
        // 模型预览
        case "model":
          bhDataSetId &&
            window.open(
              `${domain}/#/blackHole/viewDataSetSingleSimple?dataSetId=${bhDataSetId}&name=${fileName}`
            );
          return;
        // 普通文件预览
        case "kkview":
          this.viewFile(fileInfo);
          return;
        default:
          break;
      }
    },

    //详情
    getDetail() {
      return new Promise((resolve, reject) => {
        let { uuid } = this.parameter;
        detailDrawingReview({ uuid })
          .then((res) => {
            let { data } = res;
            this.form = {
              uuid: data?.uuid,
              //项目名称
              proCode: data?.proCode,
              //交底名称
              name: data?.name,
              //时间
              time: data?.time,
              //地点
              location: data?.location,
              //专业
              major: data?.major,
              //图纸/模型
              fileSource: data?.fileSource,
              //引用
              type: data?.type,
              //引用文件
              quoteFiles: data?.quoteFiles ?? "",
              //图纸会审纪要
              jointReview: JSON.parse(data?.jointReview ?? "[]"),
              //其他文件
              otherDocuments: JSON.parse(data?.otherDocuments ?? "[]"),
              //备注
              remark: data?.remark,
              //参会人员
              participantsIds: data?.participantsIds.split(",") ?? [],
              //审批状态
              approveStatus: data?.approveStatus,
            };
            //查询参会人员
            this.getPeopleData();
            //图纸模型
            this.getUploadTreeData();
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },

    //查询所有项目
    getProjectData() {
      return new Promise((resolve, reject) => {
        getAllProListByQX()
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询专业
    getTypeData() {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: "major" })
          .then((res) => {
            let { data } = res;
            this.majorSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.majorSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询参会人员
    getPeopleData() {
      let { proCode } = this.form;
      return new Promise((resolve, reject) => {
        participantsList({ pro_code: proCode })
          .then((res) => {
            let { data } = res;
            this.participantsSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.participantsSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询上传树形数据
    getUploadTreeData() {
      let { proCode, uuid = "", fileSource } = this.form;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/drawingReview/getTreeByProCodeInner`,
            {
              proCode,
              uuid,
              type: this.pageModule,
              addClassifyIdLs: [],
              deleteClassifyIdLs: [],
              fileSource,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            let source = data ?? [];
            let flatData = flatTreeData(source, "children");
            this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "children"
            );
            this.treeData = filterData ?? [];
            //
            this.currentTreeNode = this.treeData?.[0] ?? {};
            this.selectedKeys = [this.currentTreeNode.uuid];
            this.handleUploadTable();
            resolve();
          })
          .catch((_) => {
            this.currentTreeNode = {};
            this.expandedKeys = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询上传表格
    handleUploadTable() {
      let { id } = this.currentTreeNode;
      let { proCode, uuid = "" } = this.form;
      if (!proCode || !id) {
        return;
      }
      this.tableLoading = true;
      axios
        .post(
          `/probusiness/bimCadFile/getListByForeignKey`,
          {
            classifyId: id,
            proCode,
            type: this.pageModule,
            uuid,
            addFileIdLs: [],
            deleteFileIdLs: [],
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.tableData = data ?? [];
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },

    //下载
    downloadFile(row, type) {
      //引用文件
      if (type == 1) {
        let { fileInfo } = row;
        // 创建一个<a>元素
        const link = document.createElement("a");
        // 设置文件的URL
        link.href = fileInfo.url;
        // 设置下载后的文件名
        link.download = fileInfo.fileName;
        // 将<a>元素添加到页面中
        document.body.appendChild(link);
        // 模拟点击<a>元素
        link.click();
        // 移除<a>元素
        document.body.removeChild(link);
      }
      //图纸会审纪要、其他文件
      else {
        let { url } = row;
        downloadDfs(url);
      }
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.handleUploadTable();
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //表单提交
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            uuid: form.uuid,
            operate: form.operate,
            reason: form.reason,
          };
          this.submitLoading = true;
          approveDrawingReview(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("审批成功", 1.5);
                this.handelCancel();
              } else {
                this.$message.error(res?.message ?? "审批失败");
              }
            })
            .catch((_) => {
              this.$message.error(_?.message ?? "审批失败");
            })
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    handelCancel() {
      this.$emit("update:visible", false);
      this.$parent.getTableData();
    },

    filterTitle() {
      let { pageOperate } = this;
      switch (pageOperate) {
        case 1:
          return "查看";
        case 2:
          return "审批";
        default:
          break;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 120px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
  /deep/.bj-upload-file {
    .choosed-file-warp {
      width: 100%;
    }
  }
  /deep/.ant-select {
    &.ant-select-disabled {
      .ant-select-selection--multiple {
        .ant-select-selection__choice {
          color: rgba(0, 0, 0, 0.65);
          border-color: #e8e8e8;
          background: #fff;
        }
      }
    }
  }
  .add-btn {
    position: absolute;
    top: 10px;
    right: 90px;
  }
  .wrapPage-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .warp-container {
      padding-right: 110px;
    }
    .base-container {
      height: 562px;
      overflow: hidden;
      display: flex;
      .base-left {
        width: 300px;
        flex-shrink: 0;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #d4d7d8;
        margin-right: 10px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        /deep/.ant-form-item {
          .ant-form-item-label {
            width: 56px;
          }
        }
        .tree-container {
          flex: 1;
          overflow: auto;
          overflow-x: hidden;
          position: relative;
          padding: 0 10px 0 10px;
          /deep/.ant-tree {
            .ant-tree-node-content-wrapper {
              &:hover {
                .operate {
                  .anticon {
                    display: inline-block !important;
                  }
                }
              }
            }
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                position: relative;
                width: calc(100% - 25px);
                padding: 0;
                .ant-tree-iconEle {
                  color: #ffca28;
                  font-size: 16px;
                }
                .ant-tree-title {
                  overflow: hidden;
                  display: inline-block;
                  width: calc(100% - 26px);
                  .custom-tree-title-warp {
                    display: flex;
                    width: 100%;
                    .title {
                      flex: 1;
                      overflow: hidden;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    }
                    .operate {
                      flex-shrink: 0;
                      margin-left: 8px;
                      color: #8c8c8c;
                      width: 59px;
                      .anticon {
                        display: none;
                      }
                      .add-file-button {
                        font-size: 15px;
                      }
                      .edit-btn {
                        margin: 0 8px;
                      }
                    }
                  }
                }
              }
            }
          }
          .ant-empty {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
      .base-right {
        flex: 1;
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        .table-file-container {
          flex: 1;
          .files-icon {
            .anticon {
              cursor: pointer;
              font-size: 18px;
              color: #1677ff;
              margin-right: 16px;
              &:last-of-type {
                margin-right: 0;
              }
            }
            .anticon-download {
              color: #239b53;
            }
            .anticon-delete {
              color: #e43d3d;
            }
          }
        }
        .table-file-pager {
          flex-shrink: 0;
        }
      }
    }
  }
}
</style>
